package start.spring.basic.util.thread;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * ****************************************************************************
 * 自定义线程名称工厂类
 *
 * @author(作者)：xuyongyun	
 * @date(创建日期)：2018年8月28日
 ******************************************************************************
 */
public class NamedThreadFactory implements ThreadFactory {
	
	private static String THREADNAME_DEFAULT = "DEFAULT_THREADNAME";

	private AtomicInteger threadNumber = new AtomicInteger(1); 
	private String threadNamePrefix;
	private Boolean isDaemon;
	private Integer priority;
	
	public NamedThreadFactory(String threadName){
		this.setThreadNamePrefix(threadName);
	}
	
	public NamedThreadFactory(String threadName,boolean isDaemon){
		this.setThreadNamePrefix(threadName);
		this.setDaemon(isDaemon);
	}
	
	public NamedThreadFactory(String threadName,int priority){
		this.setThreadNamePrefix(threadName);
		this.setPriority(priority);
	}
	
	public NamedThreadFactory(String threadName,boolean isDaemon,int priority){
		this.setThreadNamePrefix(threadName);
		this.setDaemon(isDaemon);
		this.setPriority(priority);
	}
	
	@Override
	public Thread newThread(Runnable r) {
		Thread t = new Thread(r,threadNamePrefix + threadNumber.getAndIncrement());
        if(isDaemon!=null){
        	t.setDaemon(isDaemon.booleanValue());
        }
        if(priority!=null){
        	t.setPriority(priority.intValue());
        }
        return t;
	}
	
	/**
	 * 设置自定义线程名称
	 * @param threadName 线程名称
	 */
	private void setThreadNamePrefix(String threadName){
		if(null == threadName || threadName.isEmpty()) { 
			threadName = THREADNAME_DEFAULT;
		} 
		threadNamePrefix = threadName + "-";
	}
	
	/**
	 * 设置是否守护线程
	 * @param isDaemon 是否守护线程 true是，false否
	 */
	private void setDaemon(boolean isDaemon){
		this.isDaemon = Boolean.valueOf(isDaemon);
	}
	
	/**
	 * 设置线程的优先级
	 * @param priority 优先级
	 */
	private void setPriority(int priority){
		if(priority < Thread.MIN_PRIORITY){
			priority = Thread.MIN_PRIORITY;
		}else if(priority > Thread.MAX_PRIORITY){
			priority = Thread.MAX_PRIORITY;
		}
		this.priority = Integer.valueOf(priority);
	}
}
